package com.ptszyxx.popose.module.main.user;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;

import com.github.gzuliyujiang.wheelpicker.OptionPicker;
import com.github.gzuliyujiang.wheelpicker.contract.OnLinkagePickedListener;
import com.github.gzuliyujiang.wheelpicker.contract.OnOptionPickedListener;
import com.luck.picture.lib.entity.LocalMedia;
import com.ptszyxx.popose.BR;
import com.ptszyxx.popose.R;
import com.ptszyxx.popose.common.constants.BundleConstant;
import com.ptszyxx.popose.common.utils.YVoiceUtil;
import com.ptszyxx.popose.databinding.FragmentUserEditBinding;
import com.ptszyxx.popose.module.main.user.adapter.UserLabelAdapter;
import com.ptszyxx.popose.module.main.user.provider.UserAddressPicker;
import com.ptszyxx.popose.module.main.user.provider.UserWorkPicker;
import com.ptszyxx.popose.module.main.user.vm.UserEditVM;
import com.ysg.base.BaseFragment;
import com.ysg.http.data.AppViewModelFactory;
import com.ysg.http.data.entity.user.AreaEntity;
import com.ysg.http.data.entity.user.CityEntity;
import com.ysg.http.data.entity.user.ProvinceEntity;
import com.ysg.http.data.entity.user.UserAuthEntity;
import com.ysg.http.data.entity.user.UserHeightEntity;
import com.ysg.http.data.entity.user.UserWorkEntity;
import com.ysg.http.data.entity.user.UserWorkItemEntity;
import com.ysg.utils.YCollectionUtil;
import com.ysg.utils.YDialogUtil;
import com.ysg.utils.YImageUtil;
import com.ysg.utils.YRecyclerViewUtil;
import com.ysg.utils.YStringUtil;
import com.ysg.widget.pic.SelectPicAdapter;
import com.ysg.widget.pic.SelectPicBean;
import com.ysg.widget.pic.SelectPicEnum;
import com.ysg.widget.pic.YPicUtils;

import java.util.ArrayList;
import java.util.List;

public class UserEditFragment extends BaseFragment<FragmentUserEditBinding, UserEditVM> {
    private SelectPicAdapter adapter;
    private UserLabelAdapter labelAdapter;
    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_user_edit;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public UserEditVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(UserEditVM.class);
    }

    @Override
    public void onPause() {
        super.onPause();
        YVoiceUtil.getInstance().stopPlay();
    }

    @Override
    public void initParam() {
        super.initParam();
        Bundle bundle = getArguments();
        if (bundle != null){
            viewModel.userId = bundle.getString(BundleConstant.USER_ID);
        }
    }

    @Override
    public void initAdapter() {
        adapter = new SelectPicAdapter(getContext(), SelectPicEnum.select);
        binding.recyclerViewPic.setLayoutManager(new GridLayoutManager(getContext(), 3));
        binding.recyclerViewPic.setAdapter(adapter);

        //记得添加权限：
        adapter.setOnSelectListener(new SelectPicAdapter.OnSelectPicListener() {
            @Override
            public void onAddPicListener() {
                YPicUtils.getInstance().addAlbumSingle(getContext(), "申请拍照权限：用于上传个人形象照", new YPicUtils.OnResultListener() {
                    @Override
                    public void onResultListener(ArrayList<LocalMedia> result) {
                        if (YCollectionUtil.isNotEmpty(result)){
                            viewModel.requestUploadXingxiang(result.get(0).getCompressPath());
                        }
                    }
                });
            }

            @Override
            public void onDeletePicListener(int position) {
                viewModel.requestXingxiangDelete(adapter.getData().get(position).getMinPic());
            }
        });

        labelAdapter = new UserLabelAdapter();
        YRecyclerViewUtil.initGrid(getContext(), binding.recyclerViewLabel, labelAdapter, 5);
    }

    private void addAdapterUI(String o) {
        SelectPicBean selectPicBean = new SelectPicBean();
        selectPicBean.setPic(o);
        selectPicBean.setMinPic(o);
        adapter.getData().add(selectPicBean);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.requestUser();
        viewModel.requestOosToken();
        viewModel.requestHeightList();
        viewModel.requestWeightList();
        viewModel.requestIncomeList();
        viewModel.requestEducationList();
        viewModel.requestWorkList();
        viewModel.requestAddressList();
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.onSelectAvatarEvent.observe(this, o -> onUpdateAvatar());
        viewModel.uc.onAvatarUIEvent.observe(this, o -> setAvatarUI());
        viewModel.uc.onBirthdayEvent.observe(this, o -> showDialogBirthday());
        viewModel.uc.onUIEvent.observe(this, o -> setUI());
        viewModel.uc.onHeightEvent.observe(this, o -> showDialogHeight(1));
        viewModel.uc.onWeightEvent.observe(this, o -> showDialogHeight(2));
        viewModel.uc.onIncomeEvent.observe(this, o -> showDialogHeight(3));
        viewModel.uc.onEducationEvent.observe(this, o -> showDialogHeight(4));
        viewModel.uc.onWorkEvent.observe(this, o -> showDialogWork());
        viewModel.uc.onAddressEvent.observe(this, o -> showDialogAddress());
        viewModel.uc.onRefreshAddPicEvent.observe(this, o -> addAdapterUI((String)o));
        viewModel.uc.onRefreshPicEvent.observe(this, o -> setAdapterUI());
    }

    private void setAvatarUI() {
        YImageUtil.show(binding.ivAvatar, viewModel.entity.getPic());
    }

    private void setAdapterUI(){
        if (YStringUtil.isNotEmpty(viewModel.entity.getXingxiang())){
            List<SelectPicBean> list = new ArrayList<>();
            for (String item: viewModel.entity.getXingxiang().split(",")) {
                if (YStringUtil.isNotEmpty(item)){
                    list.add(new SelectPicBean(item, item));
                }
            }
            adapter.getData().addAll(list);
            adapter.notifyDataSetChanged();
        }
    }


    private void setUI() {
        try {
            if (YStringUtil.isNotEmpty(viewModel.entity.getNick())){
                binding.tvName.setContent(viewModel.entity.getNick());
            }
            if (YStringUtil.isNotEmpty(viewModel.entity.getMysign())){
                binding.tvSign.setContent(viewModel.entity.getMysign());
            }
            if (YStringUtil.isNotEmpty(viewModel.entity.getBirthday())){
                binding.tvBirthday.setContent(viewModel.entity.getBirthday());
            }
            if (YStringUtil.isNotEmpty(viewModel.entity.getShengao())){
                binding.tvHeight.setContent(viewModel.entity.getShengao());
            }
            if (YStringUtil.isNotEmpty(viewModel.entity.getTizhong())){
                binding.tvWeight.setContent(viewModel.entity.getTizhong());
            }
            if (YStringUtil.isNotEmpty(viewModel.entity.getNianshouru())){
                binding.tvIncome.setContent(viewModel.entity.getNianshouru());
            }
            if (YStringUtil.isNotEmpty(viewModel.entity.getEduStatusRu())){
                binding.tvEducation.setContent(viewModel.entity.getEduStatusRu());
            }
            if (YStringUtil.isNotEmpty(viewModel.entity.getZhiyename())){
                binding.tvWork.setContent(viewModel.entity.getZhiyename());
            }
            if (YStringUtil.isNotEmpty(viewModel.entity.getAddress())){
                binding.tvAddress.setContent(viewModel.entity.getAddress());
            }
            if (YStringUtil.isNotEmpty(viewModel.entity.getBiaoqianname())){
                List<String> labelList = new ArrayList<>();
                for (String label: viewModel.entity.getBiaoqianname().split(",")) {
                    labelList.add(label);
                }
                labelAdapter.setList(labelList);
            }

            List<UserAuthEntity> userAuthDtoList = viewModel.entity.getUserAuthDtoList();
            for (int i = 0; i < userAuthDtoList.size(); i++) {
                if (userAuthDtoList.get(i).getAuthNameEn().equals("VOICE")) {
                    UserAuthEntity userAuthDtoListBean = userAuthDtoList.get(i);
                    int status = userAuthDtoListBean.getStatus();
                    if (status == 2) {
                        binding.tvRecordVoice.setText(getResources().getString(R.string.user_edit_audio_sign_record_again));
                        binding.tvSignTip.setVisibility(View.GONE);
                        binding.voiceView.setVisibility(View.VISIBLE);
                    } else if (status == 1) {
                        binding.tvRecordVoice.setText(getResources().getString(R.string.user_edit_audio_sign_record_approve));
                        binding.tvSignTip.setVisibility(View.VISIBLE);
                        binding.voiceView.setVisibility(View.GONE);
                        binding.tvRecordVoice.setClickable(false);
                    } else {
                        binding.voiceView.setVisibility(View.GONE);
                        binding.tvSignTip.setVisibility(View.VISIBLE);
                        binding.tvRecordVoice.setText(getResources().getString(R.string.user_edit_audio_sign_record));
                    }
                }
            }

            if (viewModel.entity.getSignatureDto() == null) {
                binding.voiceView.setVisibility(View.GONE);
            } else {
                if (!TextUtils.isEmpty(viewModel.entity.getSignatureDto().getVoiceUrl())) {
                    binding.tvVoiceSignTip.setVisibility(View.GONE);
                    viewModel.voiceUrl = viewModel.entity.getSignatureDto().getVoiceUrl();
                    binding.voiceView.setData(viewModel.voiceUrl, viewModel.entity.getSignatureDto().getSeconds()+"");
                }
            }
        }catch (Exception e){
        }

    }

    /**
     * 修改头像
     */
    private void onUpdateAvatar() {
        YPicUtils.getInstance().addAvatar(getContext(), new YPicUtils.OnResultListener() {
            @Override
            public void onResultListener(ArrayList<LocalMedia> result) {
                if (YCollectionUtil.isNotEmpty(result)){
                    viewModel.requestOosUploadPic(result.get(0).getCompressPath(), true);
                }
            }
        });
    }

    private void showDialogBirthday() {
        YDialogUtil.getInstance().showDialogDate(getActivity(), s -> {
            viewModel.updateBirthday(s);
        });
    }

    private void showDialogHeight(int type) {
        List<String> list = new ArrayList<>();
        OptionPicker picker = new OptionPicker(getActivity());
        switch (type){
            case 1:
                for (UserHeightEntity item :viewModel.heightList) {
                    list.add(item.getValue());
                }
                if (YStringUtil.isNotEmpty(viewModel.entity.getShengao())){
                    picker.setDefaultValue(viewModel.entity.getShengao());
                }
                break;
            case 2:
                for (UserHeightEntity item :viewModel.weightList) {
                    list.add(item.getValue());
                }
                if (YStringUtil.isNotEmpty(viewModel.entity.getTizhong())){
                    picker.setDefaultValue(viewModel.entity.getTizhong());
                }
            case 3:
                for (UserHeightEntity item :viewModel.incomeList) {
                    list.add(item.getValue());
                }
                if (YStringUtil.isNotEmpty(viewModel.entity.getNianshouru())){
                    picker.setDefaultValue(viewModel.entity.getNianshouru());
                }
                break;
            case 4:
                for (UserHeightEntity item :viewModel.educationList) {
                    list.add(item.getValue());
                }
                if (YStringUtil.isNotEmpty(viewModel.entity.getEduStatusRu())){
                    picker.setDefaultValue(viewModel.entity.getEduStatusRu());
                }
                break;
        }
        picker.setData(list);
        picker.setOnOptionPickedListener(new OnOptionPickedListener() {
            @Override
            public void onOptionPicked(int position, Object item) {
                switch (type){
                    case 1:
                        viewModel.requestHeight(type, viewModel.heightList.get(position));
                        break;
                    case 2:
                        viewModel.requestHeight(type, viewModel.weightList.get(position));
                        break;
                    case 3:
                        viewModel.requestHeight(type, viewModel.incomeList.get(position));
                        break;
                    case 4:
                        viewModel.requestHeight(type, viewModel.educationList.get(position));
                        break;
                }
            }
        });
        picker.show();
    }

    private void showDialogWork() {
        UserWorkPicker picker = new UserWorkPicker(getActivity(), viewModel.workList);
        picker.setOnLinkagePickedListener(new OnLinkagePickedListener() {
            @Override
            public void onLinkagePicked(Object first, Object second, Object third) {
                Log.e("first", ""+first);
                Log.e("second", ""+second);
                Log.e("third", ""+third);
                try {
                    UserWorkItemEntity itemEntity = null;
                    for (UserWorkEntity data: viewModel.workList) {
                        List<UserWorkItemEntity> items = data.getZhiyeList();
                        for (UserWorkItemEntity item: items) {
                            if (YStringUtil.eq(item.getName(), second)) {
                                itemEntity = item;
                                break;
                            }
                        }
                        if (YStringUtil.eq(data.getName(), first)) {
                            break;
                        }
                    }
                    viewModel.requestWork(itemEntity);
                }catch (Exception e){}
            }
        });
        picker.show();
    }

    private void showDialogAddress() {
        UserAddressPicker picker = new UserAddressPicker(getActivity(), viewModel.addressResult);
        picker.setOnLinkagePickedListener(new OnLinkagePickedListener() {
            @Override
            public void onLinkagePicked(Object first, Object second, Object third) {
//                Log.e("first", ""+first);
//                Log.e("second", ""+second);
//                Log.e("third", ""+third);
                try {
                    ProvinceEntity provinceEntity = null;
                    CityEntity cityEntity = null;
                    AreaEntity areaEntity = null;
                    for (ProvinceEntity province: viewModel.addressResult.getList()) {
                        for (CityEntity city: province.getCitiesList()) {
                            for (AreaEntity area: city.getAreaList()) {
                                if (YStringUtil.eq(area.getName(), third)) {
                                    areaEntity = area;
                                    break;
                                }
                            }
                            if (YStringUtil.eq(city.getCity(), second)) {
                                cityEntity = city;
                                break;
                            }
                        }
                        if (YStringUtil.eq(province.getProvince(), first)) {
                            provinceEntity = province;
                            break;
                        }
                    }
                    viewModel.requestAddress(provinceEntity, cityEntity, areaEntity);
                }catch (Exception e){
                }
            }
        });
        picker.show();
    }



}
